package gold.digger;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC402 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String removeKdigits(String num, int k) {
            if (num.length() <= k) return "0";

            StringBuilder res = new StringBuilder();
            Deque<Character> deque = new LinkedList<>();
            int size = num.length() - k;

            for (int i = 0; i < num.length(); i++) {
                char ch = num.charAt(i);
                while (k > 0 && !deque.isEmpty() && deque.peekLast() > ch) {
                    deque.pollLast();
                    --k;
                }

                deque.offerLast(ch);
            }

            while (k-- > 0) deque.pollLast();
            while (deque.size() > 1 && deque.peekFirst().charValue() == '0') {
                deque.pollFirst();
            }

            while (!deque.isEmpty()) {
                res.append(deque.pollFirst());
            }

            return res.toString();
        }
    }

    public void run() {
        Solution solution = new Solution();
        System.out.println(solution.removeKdigits("10200", 1));
    }

    public static void main(String[] args) throws Exception {
        LC402 an = new LC402();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
